# language_utils.py
import json
import tkinter as tk
from tkinter import ttk

# ------------------------- 语言管理器 -------------------------
class LanguageManager:
    _instance = None
    
    def __new__(cls):
        """单例模式实现方法，控制实例的创建过程"""
        if not cls._instance:  # 检查是否已存在实例
            # 创建新实例（首次调用时）
            cls._instance = super().__new__(cls)
            # 初始化实例属性
            cls._instance.current_lang = "zh"  # 设置默认语言为英文
            cls._instance.texts = {}  # 初始化空翻译字典
            cls._instance.load_language()  # 加载语言文件
            cls._instance.callbacks = []  # 初始化回调函数列表
        return cls._instance  # 总是返回同一个实例
    

    def load_language(self, lang=None):
        """加载指定语言或当前语言的翻译文本
        
        参数:
            lang (str, optional): 要加载的语言代码(如'en','zh')，不传则使用当前语言
            
        异常处理:
            捕获所有异常并打印错误信息，出错时清空翻译文本
        """
        try:
            # 打开语言文件
            with open('lang.json', 'r', encoding='utf-8') as f:
                # 读取所有语言数据
                all_langs = json.load(f)
                # 更新当前语言(如果传入了新语言则使用新语言，否则保持原语言)
                self.current_lang = lang or self.current_lang
                # 提取当前语言的翻译文本
                self.texts = all_langs[self.current_lang]
        except Exception as e:
            # 错误处理：打印错误并清空翻译文本
            print(f"语言加载错误: {str(e)}")
            self.texts = {}  # 确保出错时有空字典作为后备


    def register_callback(self, callback):
        """注册语言切换回调函数"""
        self.callbacks.append(callback)

    def switch_language(self, lang):
        """切换语言并触发所有回调"""
        self.current_lang = lang
        self.load_language()
        for cb in self.callbacks:
            cb()

    def get_text(self, *path):
        """安全获取嵌套翻译文本"""
        result = self.texts
        try:
            for key in path:
                result = result[key]
            return result
        except (KeyError, TypeError):
            return "MISSING_TRANSLATION"

# ------------------------- 语言切换器 -------------------------
class LanguageSwitcher(ttk.Frame):
    def __init__(self, parent, position="bottom-left"):
        super().__init__(parent)
        self.lang_manager = LanguageManager()

        # 添加语言选择标签
        self.label = ttk.Label(self, text=self.lang_manager.get_text("common", "language_label"))
        self.label.pack(side=tk.LEFT, padx=(0, 5))
        
        # 创建组合框
        self.combo = ttk.Combobox(
            self,
            values=self.lang_manager.get_text("common", "languages"),
            state="readonly"
        )
        self._update_combo_value()
        self.combo.pack(side=tk.LEFT, padx=5)      
        # 绑定事件
        self.combo.bind("<<ComboboxSelected>>", self.on_language_change)
        
        # 设置初始位置
        self.position_widget(position)
        
        # 注册自身更新回调
        self.lang_manager.register_callback(self._update_ui)

    def position_widget(self, position):
        """定位组件到指定区域"""
        pack_options = {
            "top-right": {"side": tk.TOP, "anchor": "ne"},
            "top-left": {"side": tk.TOP, "anchor": "nw"},
            "bottom-right": {"side": tk.BOTTOM, "anchor": "se"},
            "bottom-left": {"side": tk.BOTTOM, "anchor": "sw"}
        }
        self.pack(**pack_options.get(position, "top-right"))

    def on_language_change(self, event):
        """处理语言切换事件"""
        new_lang = "zh" if self.combo.get() == "中文" else "en"
        print(f"Language changed to {new_lang}")
        self.lang_manager.switch_language(new_lang)

    def _update_combo_value(self):
        """更新下拉框显示值"""
        current_display = "中文" if self.lang_manager.current_lang == "zh" else "English"
        self.combo.set(current_display)

    def _update_ui(self):
        """语言切换后更新组件自身"""
        self._update_combo_value()
        # 更新下拉框选项的显示语言
        self.combo["values"] = self.lang_manager.get_text("common", "languages")
        self.label["text"] = self.lang_manager.get_text("common", "language_label")


        
"""
# ------------------------- 示例使用 -------------------------
if __name__ == "__main__":
    # 测试代码
    root = tk.Tk()
    root.geometry("800x600")
    switcher = LanguageSwitcher(root, position="bottom-right")
    switcher.pack()  # 确保父容器有布局
    root.mainloop()
"""